const HomeDramas = require("../models/HomeDramas")

const addHomeDrama = async (req, res) => {
    try {
        const found = await HomeDramas.findOne({ type: req.body.type, id_drama: req.body.id_drama });
        if (found && (found.num != req.body.num)) {
            return res.status(400).json({ error_msg: "剧本重复" });
        }
        const HomeDramafound = await HomeDramas.findOne({ type: req.body.type, num: req.body.num });
        if (HomeDramafound) {
            HomeDramafound.id_drama = req.body.id_drama
            const HomeDramasave = await HomeDramafound.save()
            return res.status(200).json({ success: HomeDramasave });
        }
        else {
            const HomeDramasave = await HomeDramas(req.body).save()
            return res.status(200).json({ success: HomeDramasave });
        }

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}


const getHomeDrama = async (req, res) => {
    try {
        const foundquery = req.query
        for (item in foundquery) {
            foundquery[item] = eval("/" + foundquery[item] + "/")
        }
        const storefound = await HomeDramas.find(foundquery).sort("num").populate("id_drama")
        if (!storefound) {
            return res.status(200).json({ error_msg: "未找到" });
        }
        return res.status(200).json({ success: storefound });
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}
module.exports = { addHomeDrama, getHomeDrama }